<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools>
        <template #left>总记录条数：{{ total }}条</template>
        <el-button
          v-check="'POINT-USER-IMPORT'"
          size="small"
          type="success"
          @click="$router.push('/import?type=employee')"
        >导入</el-button>
        <el-button
          v-check="'POINT-USER-EXPORT'"
          size="small"
          type="warning"
          @click="exportExcel"
        >导出</el-button>
        <el-button
          size="small"
          type="primary"
          @click="showDialog = true"
        >新增员工</el-button>
      </PageTools>
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column
            label="序号"
            type="index"
            width="100"
            align="center"
          />
          <el-table-column label="姓名" prop="username" align="center" />
          <el-table-column label="头像" align="center">
            <template v-slot="{row}">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                width="80"
                height="80"
                :src="row.staffPhoto"
                alt=""
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" align="center" />
          <!-- <el-table-column
            label="聘用形式"
            align="center"
          >
            <template v-slot="{row}">
              {{ row.formOfEmployment === 1 ? '正式': '非正式' }}
            </template>
          </el-table-column> -->
          <el-table-column
            label="聘用形式"
            align="center"
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" prop="departmentName" align="center" />
          <el-table-column label="入职时间" align="center">
            <template v-slot="{row}">
              {{ row.timeOfEntry | time }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" align="center">
            <template v-slot="{row}">
              {{ row.enableState === 1 ? '可用': '禁用' }}
              <!-- <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              /> -->
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template v-slot="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${ row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assign(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-row type="flex" justify="end" style="margin-top: 20px;">
          <el-pagination
            layout="prev, pager, next, jumper"
            :total="total"
            background
            :page-size="size"
            :current-page="page"
            @current-change="changeFn"
          />
        </el-row>
      </el-card>
      <AddEmployee
        :show-dialog.sync="showDialog"
        @getEmployeeList="getEmployeeList"
      />
      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 二维码 -->
      <!-- 渲染组件，需要传两个值 分配角色 -->
      <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { delEmployee, getEmployeeList } from '@/api/employess'
import employeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee'
import moment from 'moment'
import Qrcode from 'qrcode'
import AssignRole from './components/AssignRole.vue'
// import { export_json_to_excel } from '@/utils/Export2Excel'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      // 存储员工信息
      list: [],
      // 存储总数量
      total: 0,
      // 当前页
      page: 1,
      // 每页的条数
      size: 5,
      loading: false,
      hireType: employeeEnum.hireType,
      showDialog: false,
      // 显示二维码的
      showCodeDialog: false,
      // 控制显示分配角色的对话框
      showRoleDialog: false,
      // 当前用户的id
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page, this.size)
      this.list = rows
      this.total = total
      this.loading = false
    },
    changeFn(value) {
      this.page = value
      // 重新发送请求
      this.getEmployeeList()
    },
    formatEmployment(row, column, cellValue, index) {
      if (cellValue === null) {
        return '其他'
      }
      return this.hireType.find(item => item.id === +cellValue).value
    },
    async del(id) {
      try {
        await this.$confirm('你确定要删除吗', '温馨提示', { type: 'warning' })
      } catch {
        return
      }
      // 发送请求删除
      await delEmployee(id)
      // 提示消息
      this.$message.success('删除员工成功')
      // 重新渲染
      this.getEmployeeList()
    },
    /*
      核心思路：
        1. 需要用到一个方法 Export2Excel 文件中的export_json_to_excel
        注意：为了性能优化，这里使用的是异步的导入
    */
    async exportExcel() {
      const excel = await import('@/utils/Export2Excel')
      // 发送ajax请求，获取所有员工的数据
      const { rows } = await getEmployeeList(1, 1000)
      // console.log(rows)
      const userRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const multiHeader = [
        ['姓名', '主要信息', '', '', '', '', '部门']
      ]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      const header = Object.keys(userRelations)
      const data = []
      // ['入职日期','手机号','姓名']
      rows.forEach(item => {
        const arr = []
        header.forEach(h => {
          // 额外判断
          if (h === '入职日期' || h === '转正日期') {
            // 只要年月日
            let time = item[userRelations[h]]
            if (time) {
              time = moment(item[userRelations[h]]).format('YYYY-MM-DD')
            }
            arr.push(time)
          } else if (h === '聘用形式') {
            const result = employeeEnum.hireType.find(v => v.id === +item[userRelations[h]])
            arr.push(result ? result.value : '其他')
          } else {
            arr.push(item[userRelations[h]])
          }
        })
        data.push(arr)
      })
      // console.log(data)
      // header: excel表头
      // data: 需要写入excel的数据
      // filename： 保存的文件名
      // autoWidth: excel的列是否自动设置宽度
      // bookType: 后缀名
      excel.export_json_to_excel({
        header,
        data,
        multiHeader, // 复杂表头
        merges, // 合并选项
        filename: '员工数据',
        autoWidth: true,
        bookType: 'xlsx'
      })
    },
    async showCode(photo) {
      this.showCodeDialog = true
      await this.$nextTick()
      Qrcode.toCanvas(this.$refs.myCanvas, photo)
    },
    assign(id) {
      // console.log(id)
      this.userId = id
      this.showRoleDialog = true
    }
  }
}

</script>

<style>

</style>
